<template>
  <div class="nurse-member-select-dialog">
    <zdyDialog
      :visible.sync="visible"
      :dialog-title="title"
      :append-to-body="true"
      :width="multiple ? '79%' : '70%'"
      :footer="multiple"
      top="3vh"
      max-height="66vh"
      @onSubmit="onSubmit"
      @close="close"
    >
      <el-row class="nurse-member-select-dialog" :gutter="20">
        <!--用户数据-->
        <el-col :span="multiple ? 19 : 24">
          <div class="filter-content">
            <div >
              <!-- 搜索 -->
              <label class="el-form-item-label">名称</label>
              <el-input v-model="query.name" clearable placeholder="名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
              <rrOperation />
            </div>
            <!--表格渲染-->
            <el-table
              ref="table"
              v-loading="crud.loading"
              :data="crud.data"
              size="small"
              style="width: 100%;"
              @select="handleSelectionChange"
              @select-all="handleSelectionAllChange"
            >
              <el-table-column v-if="multiple" key="selection" type="selection" width="55" />
              <el-table-column prop="deptSort" label="排序" />
              <el-table-column prop="name" label="单位名称名称" />
              <el-table-column prop="enabled" label="状态">
                <template slot-scope="scope">
                  {{ dict.label.dept_status[scope.row.enabled] }}
                </template>
              </el-table-column>
              <el-table-column prop="createBy" label="创建人" />

              <el-table-column prop="createTime" label="创建日期">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="updateBy" label="更新人" />
              <el-table-column prop="updateTime" label="更新时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="!multiple" label="操作" width="150px" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" @click="tableSelect(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--分页组件-->
            <pagination />
          </div>
        </el-col>
        <!-- 已选单位 -->
        <el-col v-show="multiple" :span="5">
          <div class="selected-member-title">已选单位（{{ Object.keys(selectedIds).length }}人）</div>
          <div class="selected-member-content">
            <el-tag
              v-for="(value, key) in selectedIds"
              :key="key"
              style="margin: 0 10px 10px 0;"
              effect="dark"
              closable
              @close="handleClose(key)"
            >{{ value }}</el-tag>
          </div>
        </el-col>
      </el-row>
    </zdyDialog>
  </div>
</template>

<script>

import crudSysDept from '@/api/system/dept'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
const defaultForm = { deptId: null, pid: null, subCount: null, name: null, deptSort: null, enabled: 'true', createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'SysDept',
  dicts: ['dept_status'],
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '单位', url: 'api/dept', idField: 'deptId', sort: 'deptSort,desc', crudMethod: { ...crudSysDept }})
  },
  props: {
    tag: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: false
    },
    selectList: {
      type: Array,
      default: null
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    nameList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      permission: {
        add: ['admin', 'sysDept:add'],
        edit: ['admin', 'sysDept:edit'],
        del: ['admin', 'sysDept:del']
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      },
      selectedIds: {},
      selectarray: []
    }
  },
  computed: {
    visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val) // visible 改变的时候通知父组件
      }
    }
  },
  watch: {
    dialogVisible: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          // if (this.nameList) {
          this.$nextTick(() => {
            this.selectedIds = {}
            const matchList = this.nameList.map(o => this.list.findIndex(e => e.id == o.id))
            this.toggleSelection(matchList.map(r => this.list[r]))
            this.setTags(this.nameList)
            this.checkMembers()
          })
          // }
        }
      }
    },
    selectedIds: {
      deep: true,
      handler(n, o) {
        //  this.$refs.multipleTable.toggleRowSelection(row);
      }
    },
    tag: {
      deep: true,
      handler(n, o) {
        // n.forEach(item => {
        //   if (!this.selectedIds[item.id]) {
        //     this.$set(this.selectedIds, item.id, item.name)
        //     this.selectarray.push(item)
        //   }
        // })
      }
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    deleteg() {},
    // 添加单位tag
    setTags(list) {
      // this.selectedIds = {}
      list.forEach(item => {
        if (!this.selectedIds[item.id]) {
          this.$set(this.selectedIds, item.id, item.name)
          this.selectarray.push(item)
        }
      })
      // this.selectarray = this.list
    },
    // 表格刷新后回显checkbox
    checkMembers() {
      if (JSON.stringify(this.selectedIds) !== '{}') {
        this.toggleSelection()
        for (const key in this.selectedIds) {
          if (Object.hasOwnProperty.call(this.selectedIds, key)) {
            for (let i = 0; i < this.list.length; i++) {
              const element = this.list[i]
              if (element.id === key) {
                this.toggleSelection([element])
              }
            }
          }
        }
      }
    },
    // 切换列表checkbox状态
    toggleSelection(rows) {
      if (this.$refs.multipleTable) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      }
    },
    close() {
      this.$refs.multipleTable.clearSelection()
      // this.selectedMember = []
      this.selectarray = []
    },
    // 关闭标签
    handleClose(tag) {
      this.$delete(this.selectedIds, tag)
      this.$nextTick(() => {
        this.checkMembers()
      })
    },
    handleSelectionChange(value, row) {
      const check = value.find(val => {
        return val.id === row.id
      })
      if (check) {
        this.setTags(value)
      } else {
        this.$delete(this.selectedIds, row.id)
        this.selectarray = value
      }
    },
    handleSelectionAllChange(value) {
      this.selectarray = []
      if (value.length > 0) {
        this.setTags(value)
      } else {
        this.list.forEach(val => {
          this.$delete(this.selectedIds, val.id)
        })
      }
      this.selectarray = value
    },
    /** 查询部门下拉树结构 */
    getMyDataScopeTreeFun() {
      return new Promise((resolve, reject) => {
        getMyDataScopeTree().then(res => {
          if (res.success) {
            this.deptOptions = []
            this.deptOptions.push(res.data.root)
            resolve(this.deptOptions)
          } else {
            reject()
          }
        })
      })
    },
    onSubmit() {
      if (Object.keys(this.selectedIds).length === 0) {
        this.$message({
          type: 'warning',
          message: '至少选择一名单位'
        })
        return
      }
      this.confirmStaffs()
    },
    confirmStaffs() {
      // const members = Object.values(this.selectedIds).join(',')
      // this.$confirm(`是否确定选择以下单位：${members}`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
          this.$emit('select', this.selectarray)
          this.$emit('update:dialogVisible', false)
        // })
        // .catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消'
        //   })
        // })
    },
    onSelect(row) {
      this.$confirm(`是否确定选择“${row.name}”为组长？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$emit('select', row)
          this.$emit('update:dialogVisible', false)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    tableSelect(row) {
      this.$emit('select', row)
    }
  }
}
</script>

<style lang="scss" scoped>
.nurse-member-select-dialog {
  .dept-container {
    padding: 10px;
    height: 66vh;
    border: 1px solid #d8d8d8;
    border-radius: 10px;
    .tree-container {
      height: calc(100% - 62px);
      overflow: auto;
    }
  }
  .selected-member-title {
    font-size: 16px;
    font-weight: bold;
    color: #666666;
    margin-bottom: 8px;
  }
  .selected-member-content {
    border: 1px solid #d9d9d9;
    border-radius: 5px;
    height: calc(66vh - 27px);
    padding: 15px;
  }
  ::v-deep .el-table-column--selection > .cell {
    padding-left: 14px;
  }
}
</style>
